package com.api.oa.services.impl;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.api.oa.common.ToolUtils;
import com.api.oa.common.UserType;
import com.api.oa.config.EmServer;
import com.api.oa.config.UserContext;
import com.api.oa.exception.BadRequestException;
import com.api.oa.mapper.OrgMapper;
import com.api.oa.mapper.YQInsEntityMapper;
import com.api.oa.mapper.YQUserMapper;
import com.api.oa.model.entity.OaOrg;
import com.api.oa.model.entity.YQInsEntity;
import com.api.oa.model.entity.YQUser;
import com.api.oa.model.vo.YQInsEntityVO;
import com.api.oa.services.YQInsEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class YQInsEntityServiceImpl implements YQInsEntityService {

    @Autowired
    private YQInsEntityMapper mapper;
    @Autowired
    private YQUserMapper yqUserMapper;

    @Autowired
    private OrgMapper orgMapper;

    @Override
    @Transactional
    public Integer add(YQInsEntity yqInsEntity) throws Exception {
        if (StrUtil.isEmpty(yqInsEntity.getInsCode())) {
            throw new BadRequestException("机构编码不能为空" + yqInsEntity);
        }
        if (!StrUtil.isEmpty(yqInsEntity.getMobilePhone()) && !PhoneUtil.isPhone(yqInsEntity.getMobilePhone())) {
            throw new BadRequestException("手机号不正确");
        }
        YQUser oneByInsCode = yqUserMapper.findOneByInsCode(yqInsEntity.getInsCode());
        if (oneByInsCode == null) {
            YQUser yqUser = new YQUser();
            yqUser.setUserType(UserType.INS); //机构
            yqUser.setCreatedAt(new Date());
            yqUser.setStatus(0);
            yqUser.setUname(yqInsEntity.getContacts());
            yqUser.setBelongInsCode(yqInsEntity.getInsCode()); //所属机构编码
            yqUser.setInsCode(yqInsEntity.getInsCode());
            yqUser.setPasswd(SecureUtil.md5("123456"));
            yqUserMapper.insert(yqUser);
            //注册环信
            String imUser = emServer.createImUser("a" + String.valueOf(yqUser.getUserId()), "123456", yqUser.getUname());
            yqUser.setEmUuid(imUser);
        } else {
            oneByInsCode.setBelongInsCode(yqInsEntity.getInsCode());
            oneByInsCode.setInsCode(yqInsEntity.getInsCode());
            oneByInsCode.setUname(yqInsEntity.getContacts());
            oneByInsCode.setPhone(yqInsEntity.getMobilePhone());
            yqUserMapper.update(oneByInsCode);
        }

        YQInsEntityVO yqIns = mapper.findOneByInsCode(yqInsEntity.getInsCode());
        if (yqIns == null) {
            throw new Exception("机构编码已经存在");
        }

        return mapper.insert(yqInsEntity);
    }


    @Autowired
    EmServer emServer;

    @Override
    @Transactional
    public Integer addBatch(List<YQInsEntity> entities) throws BadRequestException {
        //参数校验一下
        for (int i = 0; i < entities.size(); i++) {
            YQInsEntity yqInsEntity = entities.get(i);
            if (StrUtil.isEmpty(yqInsEntity.getInsCode())) {
                throw new BadRequestException("机构编码不能为空" + yqInsEntity);
            }
            if (!StrUtil.isEmpty(yqInsEntity.getMobilePhone()) && !PhoneUtil.isPhone(yqInsEntity.getMobilePhone())) {
                throw new BadRequestException("手机号不正确");
            }

        }
        if (entities.size() != entities.stream().map(YQInsEntity::getInsCode).distinct().count()) {
            throw new BadRequestException("机构编码有重复");
        }
        for (int i = 0; i < entities.size(); i++) {
            YQInsEntity yqInsEntity = entities.get(i);
            YQInsEntity one = mapper.findOne(yqInsEntity.getInsCode());
            if (one == null) {
                mapper.insert(yqInsEntity);
            } else {
                mapper.update(yqInsEntity);
            }
            YQUser oneByInsCode = yqUserMapper.findOneByInsCode(yqInsEntity.getInsCode());
            if (oneByInsCode == null) {
                YQUser yqUser = new YQUser();
                yqUser.setUserType(UserType.INS); //机构
                yqUser.setCreatedAt(new Date());
                yqUser.setStatus(0);
                yqUser.setUname(yqInsEntity.getContacts());
                yqUser.setBelongInsCode(yqInsEntity.getInsCode()); //所属机构编码
                yqUser.setInsCode(yqInsEntity.getInsCode());
                yqUser.setPasswd(SecureUtil.md5("123456"));
                yqUserMapper.insert(yqUser);
                //注册环信
                String imUser = emServer.createImUser("a" + String.valueOf(yqUser.getUserId()), "123456", yqUser.getUname());
                yqUser.setEmUuid(imUser);

            } else {
                oneByInsCode.setBelongInsCode(yqInsEntity.getInsCode());
                oneByInsCode.setInsCode(yqInsEntity.getInsCode());
                oneByInsCode.setUname(yqInsEntity.getContacts());
                oneByInsCode.setPhone(yqInsEntity.getMobilePhone());
                yqUserMapper.update(oneByInsCode);
            }

        }
        return 1;
    }

    @Override
    public void remove(String id) {
        mapper.delete(id);
    }

    @Override
    public Integer update(YQInsEntity entity) {
        return mapper.update(entity);
    }

    @Override
    public PageInfo<YQInsEntityVO> list(Long pid, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc,insCode desc");
        return new PageInfo<>(mapper.list(pid));
    }

    @Override
    public YQInsEntity one(String id) {
        if (UserContext.getRole() == UserType.INS) {
            id = UserContext.getInsCode();
        }
        return mapper.findOne(id);
    }

    @Override
    public PageInfo<YQInsEntityVO> page(String insCode, String orgId, Integer pageIndex, Integer pageSize) {

        if (UserContext.getRole() == UserType.INS) {
            insCode = UserContext.getInsCode(); //只有机构 才会有值
        }
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc,insCode desc");
        return new PageInfo<>(mapper.page(insCode, orgId));
    }

    @Override
    public List<YQInsEntityVO> search(String insName) {
        return mapper.search(insName);
    }

    @Override
    public PageInfo<YQInsEntityVO> androidPage(String insCode, String orgId, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc,insCode desc");
        return new PageInfo<>(mapper.page(insCode, orgId));
    }

    @Override
    public List<YQInsEntityVO> listInsByOrgId(String id) throws Exception {
        Long relate = orgMapper.findRelate(UserContext.getUserId() + "");
        if (relate == null) throw new Exception("机构为分入网格");
        OaOrg nearOne = orgMapper.findNearOne(Long.parseLong(id), relate, null);
        if (nearOne == null) throw new Exception("不可跨机构通信");
        return mapper.listInsByOrgId(id);
    }

    @Override
    public void export(String insCode, String orgId, Integer pageIndex, Integer pageSize, HttpServletResponse res) throws IOException {
        List<YQInsEntityVO> page = mapper.page(insCode, orgId);
        List<Map<String, Object>> collect = page.stream().map(i -> {
            Map<String, Object> map = new HashMap<>();
            map.put("机构名称", i.getInsName());
            map.put("机构编码", i.getInsCode());
            map.put("护理类型", i.getCareType());
            map.put("联系人", i.getContacts());
            map.put("联系方式", i.getFixedPhone());
            map.put("机构地址", i.getInsAddress());
            map.put("经度", i.getLat());
            map.put("纬度", i.getLng());
            map.put("门店照片", i.getShopImage());
            map.put("营业时间", i.getOpenTime());
            map.put("机构简介", i.getInsInfo());
            map.put("医生人数", i.getMedTotal());
            map.put("护士人数", i.getNurTotal());
            map.put("护工人数", i.getCareTotal());
            map.put("病患人员", i.getPatientTotal());
            return map;
        }).collect(Collectors.toList());
        ToolUtils.downLoadExcel(collect, res);

    }


}
